package github.ziwukun.jsonql.lang;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import github.ziwukun.jsonql.utils.CollectionUtils;

public class SelectBuilder {
	List<SelectItemBuilder> selects = new LinkedList<>();
	SelectBuilder(){}
	
	public SelectBuilder props(String prop, String... props) {
		Set<String> propSet = CollectionUtils.toSet(prop, props);
		for (String p : propSet) {
			// 检查属性是否已经添加过
			boolean contain = CollectionUtils.contains(selects, selectItem -> {
				return selectItem.prop.equals(p);
			});
			// 没有添加过就添加
			if (contain) {
				throw new JSONQLBuildException("重复添加相同名称的属性" + p);
			}
			// 添加属性
			this.selects.add(new SelectItemBuilder(p));
		}
		return this;
	}
	
	/**
	 * 添加一个属性，并且可以设置属性的子属性
	 * 
	 * @param property
	 * @param consumer
	 * @return
	 */
	public SelectBuilder prop(String prop, Consumer<SelectBuilder> consumer) {
		SelectBuilder newBuilder = new SelectBuilder();
		consumer.accept(newBuilder);

		SelectItemBuilder propItem = getProp(prop);
		propItem.addChilds(newBuilder.selects);
		return this;
	}
	
	public Select build() {
		List<SelectItem> selects = new LinkedList<>();
		for(SelectItemBuilder selectItem:this.selects) {
			selects.add(selectItem.build());
		}
		
		return new SelectImpl(selects);
	}
	
	/**
	 * 获取属性元素<br>
	 * 如果没有就创建一个
	 */
	private SelectItemBuilder getProp(String prop) {
		SelectItemBuilder item = CollectionUtils.findOne(selects, s -> {
			return s.prop.equals(prop);
		});

		if (item == null) {
			item = new SelectItemBuilder(prop);
			selects.add(item);
		}
		
		return item;
	}
}
